<?php

namespace app\api\controller\paotui;

use addons\paotui\service\Third;
use app\admin\model\paotui\Config;
use app\common\controller\Api;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\HttpException;
use think\Db;
use fast\Http;
use fast\WXBizDataCrypt;
use app\admin\model\paotui\Third as UserThird;
/**
 * 会员接口
 */
class User extends Api
{
    protected $noNeedLogin = ['oauthMiniUser','get_school_station','userschools1','getDistance'];
    protected $noNeedRight = '*';
    protected $appid='wxa0e2ffa6febd8f0b';
	protected $appsecret='5060b0321d418ce58a301d5488d0d7ca';
    public function _initialize()
    {
        parent::_initialize();
    }


    //小程序登录
    public function oauthMiniUser(){

        $configModel = new Config();
        $config = $configModel->where(['group'=>'mini'])->column("name,value");

        $code = $this->request->request("code");
		if(!$code)$code=$this->request->param('code');
        $options = [
            'app_id'   => $config['mini_appid'],
            'secret'   => $config['mini_appsecret'],
        ];

        try {
            $app = Factory::miniProgram($options);
            $sns = $app->auth->session($code);

            if(!empty($sns['openid'])){
                $result = [
                    'openid'        => $sns['openid'],
                    // 'nickname'      => "新用户"
                ];

                $loginret = Third::connect('miniapp', $result);
                if ($loginret) {
                    $userinfo = $this->auth->getUserinfo();
                    $data = [
                        'user_id'=> $userinfo['user_id'],
                        'mobile'  => $userinfo['mobile'],
                        'token'  => $userinfo['token'],
                    ];
                    $this->success(__('Logged in successful'), $data);

                }else{
                    $this->error(Third::$error);
                }
            }else{
                $this->error(Third::$error);
            }
        }catch (HttpException $e){
            $this->error($e->getMessage());
        }

    }

    /**
     * 获取用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function info(){
        
        $userModel = new \app\common\model\User();
        $userInfo = $userModel
            ->alias("user")
            ->join("paotui_user_level","user.id=paotui_user_level.user_id","left")
            ->join("paotui_level","paotui_user_level.level_id=paotui_level.id","left")
            ->where(['user.id'=>$this->auth->id])->field("user.id,user.nickname,user.avatar,user.mobile,paotui_level.level_name")->find();
        $this->success('请求成功',$userInfo);
    }
    
    /**
     * 根据token获取用户信息
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function infotoken(){
        
        $userModel = new \app\common\model\User();
        $userInfo = $userModel
            ->alias("user")
            ->join("paotui_user_level","user.id=paotui_user_level.user_id","left")
            ->join("paotui_level","paotui_user_level.level_id=paotui_level.id","left")
            ->where(['user.id'=>$this->auth->id])->field("user.id,user.nickname,user.avatar,user.mobile,paotui_level.level_name")->find();
		$wechatUser = UserThird::get(['user_id'=>$this->auth->id]);
		$openid='';
		if($wechatUser)$openid=$wechatUser['openid'];
		$userInfo['openid']=$openid;
        $this->success('请求成功',$userInfo);
    }
    
    
    /**
     * 获取用户学校信息
     * 
     */
    public function userschools(){
        $po =  $this->request->post();
        if($po['city']['location']){
            $user_school = Db::name('user_school')->where(['user_id'=>$this->auth->id])->select();
            $main = 0;
            $maindistance = 0;
            foreach($user_school as $k=>&$v){
                $schoolname = Db::name('school')->where(['id'=>$v['school_id']])->find();
                
                // $distance = abs($schoolname['lng']-$po['city']['location']['lng']) + abs($schoolname['lat']-$po['city']['location']['lat']);
                $distance = $this->getDistance($po['city']['location']['lat'],$po['city']['location']['lng'],$schoolname['lat'],$schoolname['lng']);
                if($k == 0){
                    $maindistance = $distance;
                    $main = $v['id'];
                }else{
                    if($maindistance>$distance){
                        $maindistance = $distance;
                        $main = $v['id'];
                    }
                }
                
                $v['school_name'] = $schoolname['name'];
                $v['image'] = $schoolname['image'];
                $build = Db::name('building')->where(['id'=>$v['building_id']])->find();
                $v['building_name'] = $build['name'];
            }
            //判断main 
            $user_school2 = Db::name('user_school')->where(['user_id'=>$this->auth->id])->update(['is_main'=>0,'updatetime'=>time()]);
            $user_school2 = Db::name('user_school')->where(['user_id'=>$this->auth->id,'id'=>$main])->update(['is_main'=>1,'updatetime'=>time()]);
        }else{
            $user_school = Db::name('user_school')->where(['user_id'=>$this->auth->id])->select();
             foreach($user_school as $k=>&$v){
                $schoolname = Db::name('school')->where(['id'=>$v['school_id']])->find();
                $v['school_name'] = $schoolname['name'];
                $v['image'] = $schoolname['image'];
                $build = Db::name('building')->where(['id'=>$v['building_id']])->find();
                $v['building_name'] = $build['name'];
            }
        }
        
        
        
        if($user_school){
            $this->success('请求成功',$user_school);
        }else{
            $this->error('暂无学校');
        }
        
    }
    /**
     * 获取用户学校信息
     * 
     */
    public function userschools1(){
        $po =  $this->request->post();
		$uid=$this->auth->id;
		$schools = Db::name('school')->whereNull('deletetime')->order('id asc')->select();
		$bul=Db::name('building')->column('id,name');
        if($po['city']['location']){
			$mainid = 0;
			$main = 0;
			$maindistance = 0;
            foreach($schools as $k=>&$v){
                // $distance = abs($v['lng']-$po['city']['location']['lng']) + abs($v['lat']-$po['city']['location']['lat']);
                //经纬度距离    
                $distance = $this->getDistance($po['city']['location']['lat'],$po['city']['location']['lng'],$v['lat'],$v['lng']);
                $v['distance']=$distance;
				$bname='';
				if($uid){
					$user_school = Db::name('user_school')->where(['user_id'=>$this->auth->id,'school_id'=>$v['id']])->find();
					$bname= $bul[$user_school['building_id']];
					if($k == 0){
					    $maindistance = $distance;
					    $main = $user_school['id'];
    					$mainid = $v['id'];
					}else{
					    if($maindistance>$distance){
    						$maindistance = $distance;
    						$main = $user_school['id'];
    						$mainid = $v['id'];
    					}
					}
					
				}
				$v['building_name'] = $bname;
            }
			$schools=array2sort($schools,'distance');
			
			if($uid && $main){
				foreach($schools as $k=>&$v){
					$is_main=0;
					if($v['id']==$mainid){
						$is_main=1;
					}
					$v['is_main']=$is_main;
				}
				//判断main 
				$user_school2 = Db::name('user_school')->where(['user_id'=>$uid])->update(['is_main'=>0,'updatetime'=>time()]);
				$user_school2 = Db::name('user_school')->where(['user_id'=>$uid,'id'=>$main])->update(['is_main'=>1,'updatetime'=>time()]);
			}
        }else{
            foreach($schools as $k=>&$v){
                $v['building_name'] = $bul[$v['building_id']];
				$bname='';
				$is_main=0;
				if($uid){
					$user_school = Db::name('user_school')->where(['user_id'=>$this->auth->id,'school_id'=>$v['id']])->find();
					$bname= $bul[$user_school['building_id']];
					$is_main=$user_school['is_main'];
				}
				$v['is_main']=$is_main;
            }
		}
        
        
        
        if($schools){
            $this->success('请求成功',$schools);
        }else{
            $this->error('暂无学校');
        }
        
    }
    //计算距离
    function getDistance($s_lat, $s_lnt, $n_lat, $n_lnt)
    {
        // 地球半径
        $r = 6378137;
        $radLat1 = deg2rad($s_lat);
    
        $radLat2 = deg2rad($n_lat);
    
        $radLnt1 = deg2rad($s_lnt);
    
        $radLnt2 = deg2rad($n_lnt);
    
        // 结果
        $s = acos(cos($radLat1) * cos($radLat2) * cos($radLnt1 - $radLnt2) + sin($radLat1) * sin($radLat2)) * $r;
        // 精度
        $s = round($s * 10000) / 10000;
        return round($s);
    }
     /**
     * 获取用户手机号
     * 
     */
    public function getmobile(){
        if($this->auth->id){
            $user = Db::name('user')->where(['id'=>$this->auth->id])->find();
            if($user){
                $this->success('请求成功',$user['mobile']);
            }else{
                $this->error('暂无学校');
            }
        }
    }
    /**
     * 获取用户学校信息
     * 
     */
    public function userschoolmain(){
        $po =  $this->request->post();
        if(!$po['id']){
            $user_school = Db::name('user_school')->where(['user_id'=>$this->auth->id,'switch'=>1])->find();
            if(!$user_school){
                $user_school = Db::name('user_school')->where(['user_id'=>$this->auth->id])->find();
            }
        }else{
            $user_school = Db::name('user_school')->where(['id'=>$po['id']])->find();
        }
            $schoolname = Db::name('school')->where(['id'=>$user_school['school_id']])->find();
            $user_school['school_name'] = $schoolname['name'];
            $user_school['image'] = $schoolname['image'];
            $build = Db::name('building')->where(['id'=>$user_school['building_id']])->find();
            $user_school['building_name'] = $build['name'];
            $this->success('请求成功',$user_school);
        
        
    }
    
    /**
     * 获取单个学校信息
     * 
     */
    public function user_school(){
        $po =  $this->request->post();
        $user_school = Db::name('user_school')->where(['id'=>$po['id']])->find();
        $this->success('请求成功',$user_school);
    }
    
    /**
     * 更改学校信息
     * 
     */
    public function changeschool(){
        $user_school = Db::name('user_school')->where(['user_id'=>$this->auth->id])->update(['is_main'=>0,'updatetime'=>time()]);
        $po =  $this->request->post();
        $user_school2 = Db::name('user_school')->where(['user_id'=>$this->auth->id,'school_id'=>$po['school']])->update(['is_main'=>1,'updatetime'=>time()]);
      
        $school = Db::name('school')->where(['id'=>$po['school']])->find();
        $this->success('成功',$school);
    }
     /**
     * 用户上传/更改楼栋学校信息
     * 
     * @param school_id 学校ID
     * @param building_id 楼栋号
     * @param name 姓名
     * @param nickname 昵称
     * @param phone 手机号
     * @param house_number 门牌号
     * 
     */
    public function adduserschool(){
        $po =  $this->request->post();
        // $user_school = Db::name('user_school')->where(['user_id'=>$this->auth->id,'school_id'=>$po['school_id']])->find();
        if(!$po['school_id']){
            $this->error('请选择学校');
        }
        if(!$po['name']){
            $this->error('请填写姓名');
        }
        if(!$po['building_id']){
            $this->error('请选择楼栋号');
        }
        if(!$po['nickname']){
            $this->error('请填写昵称');
        }
        if(!$po['phone']){
            $this->error('请填写手机号');
        }
        if(!$po['house_number']){
            $this->error('请填写门牌号');
        }
        if (!preg_match("/^1[3456789]\d{9}$/", $po['phone'])) {
             $this->error('请填写正确的手机号');
        }
        $data = [
            'school_id'=>$po['school_id'],
            'building_id'=>$po['building_id'],
            'name'=>$po['name'],
            'nickname'=>$po['nickname'],
            'phone'=>$po['phone'],
            'house_number'=>$po['house_number'],
            'user_id'=>$this->auth->id,
            'switch'=>$po['switch']
            ];
        if($po['switch'] == 1){
            $allswitch = Db::name('user_school')->where(['user_id'=>$this->auth->id,'switch'=>1])->update(['switch'=>0,'updatetime'=>time()]);   
        }    
        if(!$po['id']){
            $main = Db::name('user_school')->where(['user_id'=>$this->auth->id,'is_main'=>1])->find();
            if(!$main){
                $data['is_main'] = 1;
            }else{
                $data['is_main'] = 0;
            }
            
            $data['createtime'] = time();
            $data['updatetime'] = time();
            $res = Db::name('user_school')->insert($data);
        }else{
            $data['updatetime'] = time();
            $res = Db::name('user_school')->where('id',$po['id'])->update($data);
        }
        
        
        
        if($res){
            $this->success('请求成功');
        }else{
            $this->error('暂无学校');
        }
        
    }
    /**
     * 删除用户所在地址
     * @ApiMethod (POST)
     * 
     */
    public function deluserschool(){
        $po =  $this->request->post();
        $res = Db::name('user_school')->where(['id'=>$po['id']])->delete();
        //设置main 
        $main = Db::name('user_school')->where(['user_id'=>$this->auth->id,'is_main'=>1])->find();
        if(!$main){
            $newmain = Db::name('user_school')->where(['user_id'=>$this->auth->id])->find();
            $newmain = Db::name('user_school')->where(['id'=>$newmain['id']])->update(['is_main'=>1]);
        }
        if($res){
            $this->success('成功',$res);
        }else{
            $this->error('删除失败');
        }
        
    } 
    /**
     * 获取用户所在学校驿站
     * @ApiMethod (POST)
     * 
     */
    public function get_school_station(){
        // $school = Db::name('user_school')->where(['user_id'=>$this->auth->id,'is_main'=>1])->find();
        
        $station = Db::name('station')->whereNull('deletetime')->select();
        $this->success('成功',$station);
    } 
    
    
    /**
     * 修改会员个人信息
     *
     * @ApiMethod (POST)
     * @param string $avatar   头像地址
     * @param string $nickname 昵称
     */
    public function profile()
    {
        $user = $this->auth->getUser();
        $nickname = $this->request->post('nickname');
        $mobile = $this->request->post('mobile');
        $avatar = $this->request->post('avatar', '', 'trim,strip_tags,htmlspecialchars');
        $user->nickname = $nickname;
        $user->mobile = $mobile;
        $user->avatar = $avatar;
        $user->save();
        $this->success();
    }

    /**
     * 授权获取手机、openid等
     */
	public function getPhone(){
		$po=request()->post();
		if(!$po['iv'] || !$po['encryptedData'] || !$po['code']){
			$this->error('参数错误');
		}else{ 
		 
			$url = 'https://api.weixin.qq.com/sns/jscode2session?appid=' . $this->appid . '&secret=' . $this->appsecret . '&js_code=' . $po['code'] . '&grant_type=authorization_code';
			
			$res=Http::get($url);
			$rx=json_decode($res,1);
			
			$pc = new WXBizDataCrypt($this->appid, $rx['session_key']);
			$errCode = $pc->decryptData($po['encryptedData'], $po['iv'], $data );
		
			if ($errCode == 0) { 
				$rs=json_decode($data,1);
				$res = Db::name('user')->where(['id'=>$this->auth->id])->update(['mobile'=>$rs['phoneNumber'],'updatetime'=>time()]);
			
				if($res){
    				$this->success('成功',$rs['phoneNumber']);
				}
			} else { 
				$this->error('错误：'.$errCode);
			}
		}
	}
}
